#include "Texture.h"
#include <assert.h>

//#undef exit;

Texture::Texture() : m_isTransparent(false)
{
	m_id = -1;
}

bool Texture::Load(const std::string& fileName)
{

	glGenTextures(1, &m_id);
	glBindTexture(GL_TEXTURE_2D, m_id);
	assert(m_id != -1);
	SDL_Surface* surf  = IMG_Load(fileName.c_str());
	assert(surf);

	unsigned char* data = (unsigned char*)surf->pixels;

	int width = surf->w;
	int height = surf->h;
	int bpp = surf->format->BytesPerPixel;

	int format = GL_RGB;

	if(bpp == 4)
	{
		format = GL_RGBA;
	}

	glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
	gluBuild2DMipmaps(GL_TEXTURE_2D, format, width, height, format, GL_UNSIGNED_BYTE, data); 

	SDL_FreeSurface(surf);

	//setting up filtering 
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
	
	glEnable(GL_TEXTURE_2D);

	return true;
}

void Texture::Draw()
{
	if(m_isTransparent)
	{
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glEnable(GL_BLEND);
	}

	glBindTexture(GL_TEXTURE_2D, m_id);
	glEnable(GL_TEXTURE_2D);
}

void Texture::EnableSphereMap()
{
	glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
	glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);

	glEnable(GL_TEXTURE_GEN_S);
	glEnable(GL_TEXTURE_GEN_T);
}

void Texture::DisableSphereMap()
{
	glDisable(GL_TEXTURE_GEN_S);
	glDisable(GL_TEXTURE_GEN_T);
}

Texture::~Texture()
{
	glDeleteTextures(1, &m_id);
}